from history_qa.models import HistoryQA
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.core.paginator import Paginator
import re


@csrf_exempt
def get_history_qa_data(request):
    start_date = request.POST.get('start_date', None)
    end_date = request.POST.get('end_date', None)
    if (not start_date) and (not end_date):
        return JsonResponse({"status": False, "code": 400, "message": "fail!", "data": []}, json_dumps_params={'ensure_ascii': False})
    if (not start_date) and end_date:
        return JsonResponse({"status": False, "code": 400, "message": "fail!", "data": []}, json_dumps_params={'ensure_ascii': False})
    if start_date and not re.match(r'(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|30|31)', start_date):
        return JsonResponse({"status": False, "code": 400, "message": "fail!", "data": []}, json_dumps_params={'ensure_ascii': False})
    if end_date and not re.match(r'(19|20)\d{2}-(0[1-9]|1[0-2])-(0[1-9]|[1-2]\d|30|31)', end_date):
        return JsonResponse({"status": False, "code": 400, "message": "fail!", "data": []}, json_dumps_params={'ensure_ascii': False})
    if start_date and (not end_date):
        start_date = start_date.strip()
        start_time = start_date + " 00:00:00" 
        end_time = start_date + " 23:59:59"
        qs = HistoryQA.objects.filter(create_time__range=(start_time, end_time))

    if start_date and end_date:
        start_date = start_date.strip()
        end_date = end_date.strip()
        start_time = start_date + " 00:00:00" 
        end_time = end_date + " 23:59:59"
        qs = HistoryQA.objects.filter(create_time__range=(start_time, end_time))
    # history_qa.create_time.strftime("%Y-%m-%d %H:%M:%S")
    dialogue_list = [{"userQuestion": history_qa.question, "smartAnswer": history_qa.answer, "feedBack": int(history_qa.feedback), "userId": history_qa.user_id, "userCheckDate": history_qa.create_time.strftime("%Y-%m-%d %H:%M:%S")} for history_qa in qs]
    print(dialogue_list)
    return JsonResponse({"status": True, "code": 200, "message": "success!", "data": dialogue_list}, json_dumps_params={'ensure_ascii': False}) 



@csrf_exempt
def get_user_dialogue(request):
    user_id = request.POST.get('user_id', None)
    pageNum = request.POST.get('pageNum', 1)
    pageSize = request.POST.get('pageSize', 20)
    if user_id is None or user_id == '':
        return JsonResponse({"status": True, "code": 401, "message": "参数user_id不能为空!", "data": []}, json_dumps_params={'ensure_ascii': False}) 
    if user_id == "":
        return JsonResponse({"status": True, "code": 200, "message": "参数user_id不能为空!", "data": []}, json_dumps_params={'ensure_ascii': False}) 
    if not isinstance(pageNum, int) and pageNum.isdigit():
        pageNum = int(pageNum)
    else:
        return JsonResponse({"status": True, "code": 401, "message": "参数pageNum只能为数字!", "data": []}, json_dumps_params={'ensure_ascii': False}) 
    qs = HistoryQA.objects.filter(user_id=user_id)
    if qs.exists():
        qs = qs.order_by('-create_time')
        total_num = len(qs)
        paginator = Paginator(qs, pageSize)
        if pageNum != 0:
            qs_page = paginator.get_page(pageNum).object_list
            qs_page = qs_page[::-1]
        else:
            qs_page = qs[::-1]
        data = [{
            "question": d.question, 
            "answer": d.answer, 
            "user_id": d.user_id, 
            "feedback": d.feedback,
            "create_time": d.create_time.strftime("%Y-%m-%d %H:%M:%S")
        } for d in qs_page]
    else:
        return JsonResponse({"status": True, "code": 200, "total": 0, "message": "当前用户不存在历史对话记录!", "data": []}, json_dumps_params={'ensure_ascii': False}) 
        
    return JsonResponse({"status": True, "code": 200, "message": "success!", "total": total_num, "data": data}, json_dumps_params={'ensure_ascii': False}) 


@csrf_exempt
def update_history_qa_feedback(request):
    condition = {}
    user_id = request.POST.get('user_id', None)
    session_id = request.POST.get('session_id', None)
    question = request.POST.get('question', None)
    answer = request.POST.get('answer', None)
    feedback = request.POST.get('feedback', None)
    if feedback is None:
        return JsonResponse({"status": True, "code": 401, "message": "参数feedback不能为空!"}, json_dumps_params={'ensure_ascii': False}) 
    try:
        if user_id:
            condition.update({"user_id": int(user_id)})
    except:
        pass
    if question:
        condition.update({"question": question})
    if answer:
        condition.update({"answer": answer})
    if session_id:
        condition.update({"session_id": session_id})
    qs = HistoryQA.objects.filter(**condition)
    if qs.exists():
        qs.update(feedback=str(feedback))
        return JsonResponse({"status": True, "code": 200, "message": "用户反馈更新成功!"}, json_dumps_params={'ensure_ascii': False}) 
    else:
        return JsonResponse({"status": True, "code": 200, "message": "当前对话记录不存在!"}, json_dumps_params={'ensure_ascii': False}) 